<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @sort-change="sortChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               @on-load="onLoad">
      <template  #menu-left>
        <el-button type="primary" icon="el-icon-plus" v-if="permission.order_add" @click="handleAdd">新 增
        </el-button>
        <!--<el-button type="danger"-->
                   <!--icon="el-icon-delete"-->
                   <!--v-if="permission.order_delete"-->
                   <!--@click="handleDelete">删 除-->
        <!--</el-button>-->
      </template>

      <template #customerNo-search="{ disabled, size }">
        <el-input v-model="search.customerNo" placeholder="请输入客户账号" type="number" oninput="value=value.replace(/^0|[^0-9]/g, '')" />
      </template>
      <template #salesDate-search="{ disabled, size }">
        <!--<div style="display: flex;flex-direction: start;">-->
          <!--<el-select v-model="search.salesDateRule" placeholder="比较" filterable clearable>-->
            <!--<el-option label="" value=""></el-option>-->
            <!--<el-option value=">" label="大于">大于 </el-option>-->
            <!--<el-option value=">=" label="大于等于">大于等于 </el-option>-->
            <!--<el-option value="=" label="等于">等于 </el-option>-->
            <!--<el-option value="!=" label="不等于">不等于 </el-option>-->
            <!--<el-option value="<=" label="小于等于">小于等于 </el-option>-->
            <!--<el-option value="<" label="小于">小于 </el-option>-->
          <!--</el-select>-->
          <!--<el-date-picker-->
                  <!--size="default"-->
                  <!--v-model="search.salesDateSearch"-->
                  <!--type="date"-->
                  <!--:format="dateFormat"-->
                  <!--:value-format="dateFormat"-->
                  <!--:unlink-panels="true"-->
                  <!--clearable-->
                  <!--placeholder="订单日期"-->
                  <!--:picker-options="pickerOptions"-->
          <!--&gt;-->
          <!--</el-date-picker>-->
        <!--</div>-->
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.salesDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="订单日期"
                @change="handleDatePickerChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
                  icon="el-icon-view"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleView(row)"
                  v-if="permission.order_view"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="复制" placement="top">
          <el-button
                  icon="DocumentCopy"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleCopy(row)"
                  v-if="permission.order_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="确认订单" placement="top" v-if="row.orderStatus =='Open'">
          <el-button
                  icon="Pointer"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleEdit(row)"
                  v-if="permission.order_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="反审核" placement="top" v-if="row.orderStatus =='Confirmed'">
          <el-button
                  icon="Stamp"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleReject(row)"
                  v-if="permission.order_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="修正查询" placement="top">
          <el-button
                  icon="List"
                  link
                  :size="size"
                  :type="type"
                  @click="() => showLog(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="订单报表" placement="top">
          <el-button
                  icon="Reading"
                  link
                  :size="size"
                  :type="type"
                  @click="() => showChoice(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top" v-if="row.orderStatus =='Open'">
          <el-button
                  icon="el-icon-delete"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowDel(row)"
                  v-if="permission.order_delete"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <order-form  ref="orderForm" @success="refreshChange()"/>
    <order-log ref="orderLog"/>
    <order-copy  ref="orderCopy" @success="refreshChange()"/>
    <!--<preview ref="preview"></preview>-->
    <el-dialog title="订单预览" append-to-body v-model="box" width="30%" @close="previewClose">
      <el-form-item label="语言">
      <el-radio-group v-model="isEnglish" class="list">

        <el-radio label="1" >中文</el-radio>
        <el-radio label="2" >英文</el-radio>
      </el-radio-group>
      </el-form-item>
      <el-form-item label="价格">
      <el-radio-group v-model="hiddenPrice" class="list">

        <el-radio label="1" >显示价格</el-radio>
        <el-radio label="2" >不显示价格</el-radio>
      </el-radio-group>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="this.box = false">取 消</el-button>
          <el-button type="primary" @click="orderReport">预 览</el-button>
        </span>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, reject, orderReport,checkCounterAudit} from "@/api/anwise/order/order";
  import {mapGetters} from "vuex";
  import orderForm from './components/order_form.vue';
  import orderLog from './components/order_log.vue';
  import orderCopy from './components/order_copy.vue';

  export default {
      components: {
          orderForm,
          orderLog,
          orderCopy
      },
    data() {
      return {
          isEnglish:'1',
          hiddenPrice:'1',
          selectId:'',
          box:false,
          form: {},
          query: {},
          salesDateRange:[],
          loading: true,
          dateFormat: 'YYYY-MM-DD',
          pickerOptions: {},
          page: {
              pageSize: 20,
              currentPage: 1,
              total: 0
          },
          search:{},
          selectionList: [],
          option: {
              height:'auto',
              calcHeight: 30,
              tip: false,
              searchShow: false,
              searchMenuSpan: 6,
              border: true,
              index: true,
              selection: true,
              reserveSelection:true,
              labelWidth: 150,
              indexWidth:100,
              menuWidth: 230,
              addBtn: false,
              editBtn: false,
              viewBtn: false,
              delBtn: false,
              stripe: true,
              searchIndex: 3,
              searchIcon: false,
            searchEnter:true,
            // selectable:(row,index)=>{
            //   return row.orderStatus =='open';
            // },
          column: [

            {
              label: "订单编号",
              prop: "idNo",
              type: "input",
                fixed: true,
                search: true,
                overHidden: true,
                sortable: true,
                width:120,
              rules: [{
                required: true,
                message: "请输入订单编号",
                trigger: "blur"
              }],
            },
              {
                  label: "版本",
                  prop: "version",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:100,
              },
              {
                  label: "客户账号",
                  prop: "customerNo",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入客户账号",
                      trigger: "blur"
                  }],
              },
              {
                  label: "订单日期",
                  prop: "salesDate",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入订单日期",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户名称",
                  prop: "customerName",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入客户名称",
                      trigger: "blur"
                  }],
              },
              {
                  label: "销售方式",
                  prop: "salesType",
                  type: "select",
                  filterable: true,
                  overHidden: true,
                  sortable: true,
                  search:true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=sales_type',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入销售方式",
                      trigger: "blur"
                  }],
              },
              {
                  label: "订单状态",
                  prop: "orderStatus",
                  type: "select",
                  filterable: true,
                  overHidden: true,
                  sortable: true,
                  search:true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=order_status',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入订单状态",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户PO",
                  prop: "custPo",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "联系人员",
                  prop: "contact",
                  type: "input",
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "业务人员",
                  prop: "serviceName",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "交货地点",
                  prop: "deliAddr",
                  type: "input",
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
            {
              label: "订单类型",
              prop: "orderType",
                type: "select",
                filterable: true,
                overHidden: true,
                sortable: true,
                search:true,
                width:120,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=order_type',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: false,
                    message: "请输入订单类型",
                    trigger: "blur"
                }],
            },
            {
              label: "交货方式",
              prop: "deliMeth",
                type: "select",
                filterable: true,
                overHidden: true,
                sortable: true,
                width:120,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=deli_type',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: false,
                    message: "请输入交货方式",
                    trigger: "blur"
                }],
            },

            {
              label: "付款条件",
              prop: "paymentTerms",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: '贸易条款',
              prop: 'tradeTerms',
              type: "input",
              overHidden: true,
              sortable: true,
              width:120,
            },
            {
              label: '运输方式',
              prop: 'tansportModes',
              type: "input",
              overHidden: true,
              sortable: true,
              width:120,
            },


              {
                  label: "币别",
                  prop: "rmb",
                  type: "select",
                  filterable: true,
                  // search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入币别",
                      trigger: "blur"
                  }],
              },
            {
              label: "公司名称",
              prop: "companyName",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },



            {
              label: "收货人员",
              prop: "consignee",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "箱唛",
              prop: "salesName",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "生产备注",
              prop: "remark",
              type: "textarea",
              span: 24,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "销售备注",
              prop: "salesRemark",
              type: "textarea",
              span: 24,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "业务电话",
              prop: "extNo",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            // {
            //   label: "订单日期",
            //   prop: "salesDate",
            //   type: "input",
            //     // search: true,
            //     overHidden: true,
            //     sortable: true,
            //     width:120,
            // },
            {
              label: "补货备注",
              prop: "buhuoRemark",
              type: "textarea",
              span: 24,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "操作人员",
              prop: "createUserName",
              filterable: true,
              type: "input",
              // hide: true,
              search:true,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "操作时间",
              prop: "createTime",
              type: "input",
              // hide: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "操作时间",
              prop: "createDate",
              type: "input",
              hide: true,
              sortable: true,
              width:150,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.order_add, false),
          viewBtn: this.validData(this.permission.order_view, false),
          delBtn: this.validData(this.permission.order_delete, false),
          editBtn: this.validData(this.permission.order_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
        handleCopy(row) {
          let title="复制订单";
          let type='edit';
          const id = row.id;
          this.$refs.orderCopy.show({
            id,
            title,
            type,
            row
          })
        },
        previewClose() {
            this.isEnglish='1';
            this.hiddenPrice='1';
            this.selectId='';
        },
        showChoice(row) {
          this.selectId= row.id;
          this.box = true;
        },
        orderReport(id) {
            orderReport(this.selectId, this.isEnglish, this.hiddenPrice).then(res => {
                if(res.data.success) {
                    console.log(res.data)
                    const file = res.data.data;
                    // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
                    const url = file.url;
                    // this.$refs.preview.open({
                    //     url: url || "",
                    //     originUrl: originUrl || ""
                    // });
                    window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
                }
            })
        },
        showLog(row) {
            this.$refs.orderLog.show(row.id);
        },
        rowClassName({row, rowindex}) {
            if (row.orderStatus ==='Open') {
                return 'row-yellow';
            }
        },
        handleView(row) {
            let title="查看订单信息";
            let type='view';
            const id = row.id;
            this.$refs.orderForm.show({
                id,
                title,
                type
            })
        },
        handleReject(row) {
            const $this = this;
            this.loading = true;
            console.log(this.permission);
            if (!this.permission.order_super) {
                checkCounterAudit(row).then(res=>{
                    this.loading = false;
                    if(res.data.success){
                        reject(row.id).then((res) => {
                            if (res.data.success) {
                                this.onLoad(this.page);
                                this.$message({
                                    type: "success",
                                    message: res.data.msg ||"操作成功!"
                                });
                            }
                        });
                    } else {
                        $this.loading = false;
                    }
                }).catch(err=> {
                    console.log(err)
                    $this.loading = false;
                })
            }else {
                reject(row.id).then((res) => {
                    if (res.data.success) {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: res.data.msg ||"操作成功!"
                        });
                    }
                });
            }
        },
        handleEdit(row) {
            let title="确认订单信息";
            let type='edit';
            const id = row.id;
            this.$refs.orderForm.show({
                id,
                title,
                type
            })
        },
        handleAdd() {
            let title="创建订单信息";
            let type='edit';
            this.$refs.orderForm.show({
                title,
                type
            })
        },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      searchReset() {
        this.query = {};
          this.salesDateRange = [];
          this.search.salesDateStart = '';
          this.search.salesDateEnd = '';
          this.search.customerNo = "";
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleDatePickerChange(value) {
            console.log(value);
            if (value) {
                this.search.salesDateStart = value[0];
                this.search.salesDateEnd = value[1];
            } else {
                this.search.salesDateStart = '';
                this.search.salesDateEnd = '';
            }
        },
    }
  };
</script>

<style>
  .row-yellow {
    background-color: rgb(255, 253, 230) !important;
    cursor: pointer;
  }

  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button{
    -webkit-appearance: none !important;
    margin: 0;
  }
</style>
